package haizhi.fruitmall.action;

import haizhi.fruitmall.util.BeanUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;

/**
 * Created by richa on 2017/9/1
 */

@Controller
@RequestMapping("/file")
public class FileController {

    @RequestMapping("/upload")
    @ResponseBody
    public String upload(HttpServletRequest request, HttpServletResponse response){
        //创建解析器
        try {
            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            //判断是否多重
            if(multipartResolver.isMultipart(request)){
                //转换
                MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;
                //取得所有文件名称
                Iterator<String> iterator = multipartRequest.getFileNames();
                //遍历
                while(iterator.hasNext()){
                    MultipartFile multipartFile = multipartRequest.getFile(iterator.next());
                    if(!multipartFile.isEmpty()){
                        String filePath = request.getSession().getServletContext().getRealPath("/static/img");
                        System.out.println(filePath);
                        String fileName = BeanUtil.newFileName(multipartFile.getOriginalFilename());
                        System.out.println(fileName);
                        File uploadFile = new File(filePath,fileName);
                        multipartFile.transferTo(uploadFile);
                    }
                }
                return "success";
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "failure";
    }
}
